package edu.suda.xsap.controller;

import com.github.pagehelper.PageInfo;
import edu.suda.xsap.common.Result;
import edu.suda.xsap.dto.MemberCardDto;
import edu.suda.xsap.dto.MemberDto;
import edu.suda.xsap.dto.MemberWithCardsDto;
import edu.suda.xsap.entity.ID;
import edu.suda.xsap.entity.Member;
import edu.suda.xsap.service.MemberService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/list")
    public Result list(
        @RequestParam(name = "page") int page,
        @RequestParam(name = "size") int size) {
        //1. 参数处理
        //2. 调用业务层方法，并做异常处理
        try {
            PageInfo<MemberWithCardsDto> memberDtos = memberService.findAll(page, size);
//            List<MemberDto> memberDtos = memberService.findAll();
            //打印数据
            //log.info("查询结果：{}", memberDtos);
            return Result.success(memberDtos);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);

        }
    }

    @GetMapping("/findById")
    public Result findById(@RequestParam(name = "id") Long id) {
        try {
            Member member = memberService.findById(id);
            return Result.success(member);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody MemberDto memberDto) {
        try {
            // 调用Service层保存会员信息
            Long memberId = memberService.addMember(memberDto);
            // 将id封装在R类返回
            return Result.success(memberId);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
    @PostMapping("/delete")
    public Result delete(@RequestBody Map<String, Long> payload) {
        try {
            Long id = payload.get("id");
            memberService.delete(id);
            return Result.success();
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @PostMapping("/bindCard")
    public Result bindCard(@RequestParam(name = "memberId") Long memberId, @RequestBody MemberCardDto memberCardDto) {
        try {
//            System.out.println("im here1");
            Long bindCard = memberService.bindCard(memberId, memberCardDto);
            return Result.success(bindCard);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
}
